#include "../logs/A_log.hpp"

using namespace Alpaca;

enum TimeGap
{
    GAP_SECOND,
    GAP_MIN,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink : public LogSink
{
public:
    RollByTimeSink(const std::string &basename, TimeGap gap_type)
        : _basename(basename)
    {
        switch (gap_type)
        {
        case GAP_SECOND:
            _gap_size = 1;
            break;
        case GAP_MIN:
            _gap_size = 60;
            break;
        case GAP_HOUR:
            _gap_size = 3600;
            break;
        case GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        std::string filename = createNewFile();
        // 创建文件所在路径
        util::File::create_directory(util::File::path(filename));
        // 打开文件
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    void log(const char *data, size_t len)
    {
        time_t t = util::Date::now();
        // 判断当前文件是否在该时间段中，否则创建新文件
        if (t / _gap_size != _cur_size)
        {
            std::string pathname = createNewFile();
            _ofs.close();
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _cur_size = t / _gap_size;
        }

        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile()
    {
        time_t t = util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900 << lt.tm_mon + 1
                 << lt.tm_mday << lt.tm_hour
                 << lt.tm_min << lt.tm_sec;
        filename << "-";
        filename << _name_count++;
        filename << ".log";
        return filename.str();
    }

private:
    size_t _name_count;
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_size;
    size_t _gap_size;
};

int main()
{
    std::unique_ptr<LoggerBuilder> builder(new GlobalLoggerBuilder());
    builder->BuildLoggerLevel(LogLevel::value::WARN);
    builder->BuildLoggerName("Async_logger");
    builder->BuildLoggerType(LoggerType::LOGGER_ASYNC);
    // builder->BuildEnableUsafeAsync();
    builder->BuildFormatter("[%c][%f:%l]%m%n");
    builder->BuildSinks<FileSink>("./logfile/async.log");
    builder->BuildSinks<StdoutSink>();
    builder->BuildSinks<RollByTimeSink>("./logfile/roll-async-by-time", GAP_SECOND);
    Logger::ptr logger = builder->build();

    size_t cur = util::Date::now();
    while (util::Date::now() < cur + 5)
    {
        logger->fatal("%s", "this is a test log");
        usleep(1000);
    }
    return 0;
}